<script setup>
import {ref, watch, onMounted, computed, shallowRef, markRaw} from "vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// eslint-disable-next-line vue/no-dupe-keys
const dialogVisible = ref(false)

// eslint-disable-next-line vue/no-dupe-keys
const tableData = ref([])

const searchText = ref('')

const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  },
  tableData: {
    type: Array,
    default: () => [],
    required: true
  },
})

const form = ref({
  id: -1,
  parent_id: 0,
  menu_type: "M",
  icon: '',
  name: '',
  perms: '',
  path: '',
  component: '',
  order_num: 1,
  remark: ''
})

const rules = ref({
  parentId: [
    {required: true, message: '请选择上级菜单'}
  ],
  name: [
    {required: true, message: '菜单名称不能为空', trigger: 'blur'}
  ]
})

const formRef = ref(null)

const initFormData = async (id) => {
  const res = await requestUtil.get('menu/action?id=' + id)
  form.value = res.data.msg
}

watch(
    () => props.dialogVisible,
    () => {
      let id = props.id;
      tableData.value = props.tableData;
      if (id !== -1) {
        initFormData(id);
      } else {
        form.value = {
          id: -1,
          parent_id: 0,
          menu_type: "M",
          icon: '',
          name: '',
          perms: '',
          path: '',
          component: '',
          order_num: 1,
          remark: ''
        }
      }
    }
)

const emits = defineEmits(['update:modelValue', 'initMenuList'])

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = await requestUtil.post('menu/save', form.value);
      let data = res.data;
      if (data.code === 200) {
        ElMessage.success('执行成功')
        formRef.value.resetFields()
        emits('initMenuList')
        handleClose()
      } else {
        ElMessage.error(data.msg)
      }
    } else {
      console.log('fail')
    }
  })
}

// 转换图标数据为数组格式
const icons = shallowRef([])
onMounted(() => {
  icons.value = Object.entries(ElementPlusIconsVue).map(([name, component]) => ({
    name,
    component: markRaw(component) // 标记组件为非响应式
  }))
})

// 新增过滤逻辑
const filteredIcons = computed(() => {
  return icons.value.filter(icon =>
      icon.name.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

const handleSelect = (iconName) => {
  form.value.icon = iconName
  dialogVisible.value = false
}
</script>

<template>
  <el-dialog
      :model-value="dialogVisible"
      :title="dialogTitle"
      style="padding: 40px; margin-top: 40px"
      width="600px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="上级菜单:" prop="parent_id">
        <el-select
            v-model="form.parent_id"
            placeholder="请选择上级菜单"
        >
          <el-option label="顶级" :value="0"></el-option>
          <template v-for="item in tableData">
            <el-option :label="item.name" :value="item.id"></el-option>
            <template v-for="child in item.children">
              <el-option :label="child.name" :value="child.id">
                <span>&nbsp;&nbsp;&nbsp;&nbsp;{{ '- ' + child.name }}</span>
              </el-option>
            </template>
          </template>
        </el-select>
      </el-form-item>

      <el-form-item label="菜单类型:" prop="menu_type" label-width="100px">
        <el-radio-group v-model="form.menu_type">
          <el-radio :label="'M'">目录</el-radio>
          <el-radio :label="'C'">菜单</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="菜单图标:" prop="icon">
        <el-input
            v-model="form.icon"
            placeholder="点击选择图标"
            readonly
            @click="dialogVisible = true"
        >
          <template #suffix>
            <component
                :is="form.icon"
                v-if="form.icon"
                style="width: 1em; height: 1em; margin-right: 5px"
            />
            <!--            <el-icon v-else>-->
            <!--              <arrow-down/>-->
            <!--            </el-icon>-->
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="菜单名称:" prop="name">
        <el-input v-model="form.name"/>
      </el-form-item>

      <el-form-item label="权限标识:" prop="perms">
        <el-input v-model="form.perms"/>
      </el-form-item>

      <el-form-item label="路由路径:" prop="component">
        <el-input v-model="form.path"/>
      </el-form-item>

      <el-form-item label="组件路径:" prop="component">
        <el-input v-model="form.component"/>
      </el-form-item>

      <el-form-item label="显示顺序:" prop="order_num">
        <el-input-number v-model="form.order_num" :min="1" label="显示顺序"/>
      </el-form-item>

      <el-form-item label="备注:" prop="remark">
        <el-input v-model="form.remark"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>


    <el-dialog
        v-model="dialogVisible"
        title="选择图标"
        style="padding: 40px; margin-top: 20px"
        width="1500px"
    >
      <!-- 新增搜索框 -->
      <el-input
          v-model="searchText"
          placeholder="输入图标名称搜索"
          clearable style="margin-bottom: 20px"
      />
      <div class="icon-grid">
        <!-- 修改循环为 filteredIcons -->
        <div
            v-for="icon in filteredIcons"
            :key="icon.name"
            class="icon-item"
            @click="handleSelect(icon.name)"
        >
          <el-icon :size="26">
            <component :is="icon.component"/>
          </el-icon>
          <span class="icon-name">{{ icon.name }}</span>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<style scoped lang="scss">
.icon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 20px;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.icon-item:hover {
  background-color: #f5f7fa;
  transform: scale(1.1);
}

.icon-name {
  margin-top: 8px;
  font-size: 12px;
  text-align: center;
  word-break: break-all;
}
</style>